package com.irdstudio.efp.nls.service.impl.psd.credit;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ExternalSysException;
import com.irdstudio.basic.framework.core.exception.OcmSystemException;
import com.irdstudio.basic.framework.core.util.DateTool;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.util.UUIDUtil;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.common.psd.PsdConstantSet;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.console.service.facade.SOrgService;
import com.irdstudio.efp.console.service.vo.SOrgVO;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.edoc.service.bo.CfcaSignInfoVO;
import com.irdstudio.efp.edoc.service.bo.ImageBizDetailVO;
import com.irdstudio.efp.edoc.service.bo.ImageBizInfoVO;
import com.irdstudio.efp.edoc.service.facade.CfcaSignInfoService;
import com.irdstudio.efp.edoc.service.facade.ImageBizDetailService;
import com.irdstudio.efp.edoc.service.facade.ImageBizInfoService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdCertUploadService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdContResult;
import com.irdstudio.efp.edoc.service.facade.signature.PsdContService;
import com.irdstudio.efp.esb.common.constant.ElectronicSignatureEnums;
import com.irdstudio.efp.esb.service.facade.sed.cfca.SedCfcaService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.dao.sx.NlsCreditInfoDao;
import com.irdstudio.efp.nls.service.domain.sx.NlsCreditInfo;
import com.irdstudio.efp.nls.service.facade.psd.NlsCreditApprovalInfoService;
import com.irdstudio.efp.nls.service.facade.psd.PsdSqsSignatureService;
import com.irdstudio.efp.nls.service.facade.psd.PsdSxCtrSignatureService;
import com.irdstudio.efp.nls.service.vo.psd.NlsCreditApprovalInfoVO;
import com.irdstudio.efp.nls.service.vo.psd.SxCtrInfo;
import com.irdstudio.efp.nls.service.vo.signature.SignatureRecordVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.irdstudio.efp.esb.common.constant.ElectronicSignatureConstant.CONT_STATUS_200;

/**
 * 普税贷授信合同签署
 *
 * @author xiaojunhui
 */
@Service("psdSxCtrSignatureService")
public class PsdSxCtrSignatureServiceImpl implements PsdSxCtrSignatureService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(PsdSxCtrSignatureServiceImpl.class);

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;

    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    private NlsCreditInfoDao nlsCreditInfoDao;

    @Autowired
    @Qualifier("sOrgService")
    private SOrgService sOrgService;

    @Autowired
    private PsdContService psdContService;

    @Autowired
    private PsdCertUploadService psdCertUploadService;

    @Autowired
    private NlsCreditApprovalInfoService nlsCreditApprovalInfoService;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private PsdSqsSignatureService sqsSignatureService;

    /**
     * 更新合同表状态为 待签订 的标志
     */
    private boolean updateCtrStatusFlag = false;

    @Override
    public String[] sxSignature(SxCtrInfo sxCtrInfo) {

        logger.info("授信合同签订获取到得信息为：[{}]", JSONObject.toJSONString(sxCtrInfo));

        NlsCreditInfo nlsCreditInfo = null;
        CtrLoanContVO ctrLoanContVO = null;
        LmtPrdContVO lmtPrdContVO = null;
        CusIndivVO custInfoVo = null;
        CfcaSignInfoVO cfcaSignInfoVO = null;
        try {
            //获取营业日
            String openday = pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001);
            if (StringUtils.isEmpty(openday)) {
                logger.error("签订授信合同流程获取到的openday为空，授信申请流水号为：[{}]",sxCtrInfo.getCrdtAppFlowNo());
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "尊敬的客户您好，由于系统异常本次签订合同失败，请您稍后再试");
            }
            //查询授信申请信息，不存在 则拒绝
            nlsCreditInfo = nlsCreditInfoDao.queryByLmtApplySeq(sxCtrInfo.getCrdtAppFlowNo());
            if (Objects.isNull(nlsCreditInfo)) {
                logger.error("签订授信合同流程获取到的授信信息为空，授信申请流水号为：[{}]",sxCtrInfo.getCrdtAppFlowNo());
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "根据授信申请流水号获取到的授信申请信息为空");
            }
            //判断是否申请成功状态
            if (!nlsCreditInfo.getApprvSts().equals("02")) {
                logger.error("签订授信合同流程获取授信申请状态不为02，授信申请流水号为：[{}]",sxCtrInfo.getCrdtAppFlowNo());
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "不合法的合同签署请求");
            }
            //判断是否审批通过超过了90天
            NlsCreditApprovalInfoVO nlsCreditApprovalInfoVO = nlsCreditApprovalInfoService.selectByPrimaryKey(nlsCreditInfo.getLmtApplySeq());
            if (!"Y".equals(nlsCreditApprovalInfoVO.getApprResult())) {
                logger.error("签订授信合同流程判断审批通过已经超过了90天，授信申请流水号为：[{}]",sxCtrInfo.getCrdtAppFlowNo());
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "不合法的合同签署请求，风控审批状态不为成功");
            }
            if (TimeUtil.compareDates(TimeUtil.addDay(new SimpleDateFormat("yyyy-MM-dd").format(nlsCreditApprovalInfoVO.getApproveTime()), 90), DateTool.getCurrentDateTime())<0) {
                logger.error("签订授信合同流程判断风控审批通过时间已经查过了90天，授信申请流水号为：[{}]",sxCtrInfo.getCrdtAppFlowNo());
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "风控审批通过时间已经超过了90天，无法进行合同签订");
            }
            //判断额度表是否存在
            lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(sxCtrInfo.getCrdtAppFlowNo());
            if (Objects.isNull(lmtPrdContVO)) {
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "根据授信申请流水号获取到的额度信息为空");
            }
            //判断查询到的额度编号跟上送的是否一致
            if (!sxCtrInfo.getCrdAgrmNo().equals(lmtPrdContVO.getLmtContNo())) {
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "额度编号跟上送的不一致");
            }
            //判断额度状态
            if (lmtPrdContVO.getLmtStatus().equals(ConsoleConstant.LIMIT_STS_00) || lmtPrdContVO.getLmtStatus().equals(ConsoleConstant.LIMIT_STS_02) || lmtPrdContVO.getLmtStatus().equals(ConsoleConstant.LIMIT_STS_03)) {
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "额度状态校验不通过，禁止签署合同");
            }
            //获取客户信息表
            custInfoVo = getCustInfo(nlsCreditInfo.getCusId());
            if (Objects.isNull(custInfoVo)) {
                throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "获取客户到的信息为空");
            }
            //根据授信申请流水号和合同类型查询合同签订记录，如果存在 并且状态拒绝
            // 101 待签订
            // 200 生效
            ctrLoanContVO = ctrLoanContService.queryContNoByLmtContNoAndContype(lmtPrdContVO.getLmtContNo(), ConsoleConstant.CONT_TYPE_01);
            if (!Objects.isNull(ctrLoanContVO)) {
                if ("200".equals(ctrLoanContVO.getContState())) {
                    throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "当前授信记录已经成功签订授信合同，无需再次申请");
                }
                if (!"101".equals(ctrLoanContVO.getContState())) {
                    throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "不为待签订状态，无法进行合同签订");
                }
            } else {
                ctrLoanContVO = insertLoanCtrContract(openday, nlsCreditInfo, lmtPrdContVO, sxCtrInfo);
            }
            //保存一条数据到签章表给定时器签署脱敏合同
            insertSqsRecord(sxCtrInfo, nlsCreditInfo, ctrLoanContVO);
            //查询签章记录 如果签章记录存在那么直接走下载流程
            CfcaSignInfoVO cfcaPkParam = new CfcaSignInfoVO();
            cfcaPkParam.setApplySeq(nlsCreditInfo.getLmtApplySeq());
            cfcaPkParam.setContNo(ctrLoanContVO.getContNo());
            List<CfcaSignInfoVO> cfcaSignInfoVOS = cfcaSignInfoService.queryByApplyAndContNo(cfcaPkParam);
            //如果存在签章记录，那么代表直接走下载流程
            if (cfcaSignInfoVOS != null && !cfcaSignInfoVOS.isEmpty()) {
                PsdContResult downResult = psdContService.downSignFile(nlsCreditInfo.getLmtApplySeq(), cfcaSignInfoVOS.get(0).getCfcaContNo(), nlsCreditInfo.getLmtApplySeq() + "_sxcont.pdf");
                logger.error("签订授信合同-合同下载完成，授信申请流水号为：[{}],下载结果为：[{}]",sxCtrInfo.getCrdtAppFlowNo(),downResult.toString());
                if (downResult.isRetFlag()) {
                    //下载成功 修改状态
                    updateCtrStatus(ctrLoanContVO, "200");
                    updateArrpvDateAndLmtDate(nlsCreditInfo, lmtPrdContVO, openday);
                    //插入表到上传表
                    insertUploadLog(downResult);
                    //插入明细表
                    insertImageBizDetail(nlsCreditInfo, PsdConstantSet.PSD_SX_CONT_TYPE, FilenameUtils.getName(downResult.getFileFullPath()),downResult.getFileFullPath());
                    insertImageBizInfo(nlsCreditInfo);
                    return new String[]{ESBConstant.SUCCESS, "授信合同签订成功"};
                }
                return new String[]{EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), downResult.getMsg()};
            }
            //判断是否没开户
            if (StringUtils.isEmpty(custInfoVo.getAxqUsrId())) {
                execute3001(nlsCreditInfo,custInfoVo);
            }
            // 调3203接口进行合同签订
            cfcaSignInfoVO = new CfcaSignInfoVO();
            // 调用cfca合同模板签章接口，给贷款合同签章
            execute3203(sxCtrInfo, nlsCreditInfo,
                    custInfoVo, ctrLoanContVO,
                    ConsoleConstant.CONT_TYPE_01,
                    cfcaSignInfoVO
            );
            //下载合同
            // 调用cfca合同下载接口
            PsdContResult downResult = psdContService.downSignFile(nlsCreditInfo.getLmtApplySeq(), cfcaSignInfoVO.getCfcaContNo(), nlsCreditInfo.getLmtApplySeq() + "_sxcont.pdf");
            logger.error("签订授信合同-合同下载完成，授信申请流水号为：[{}],下载结果为：[{}]",sxCtrInfo.getCrdtAppFlowNo(),downResult.toString());
            if (downResult.isRetFlag()) {
                //下载成功 修改状态
                updateCtrStatus(ctrLoanContVO, "200");
                updateArrpvDateAndLmtDate(nlsCreditInfo, lmtPrdContVO, openday);
                insertUploadLog(downResult);
                //插入明细表
                insertImageBizDetail(nlsCreditInfo, PsdConstantSet.PSD_SX_CONT_TYPE, FilenameUtils.getName(downResult.getFileFullPath()),downResult.getFileFullPath());
                insertImageBizInfo(nlsCreditInfo);
            }else {
                return new String[]{EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), "尊敬的客户您好，由于系统在处理合同下载出现了异常，请您稍后再试"};
            }
            return new String[]{ESBConstant.SUCCESS, "授信合同签订成功"};
        } catch (BizException e) {
            logger.info("普税贷授信合同签订发生异常：", e);
            return new String[]{e.getErrorCode(), e.getMessage()};
        } catch (Exception e) {
            logger.info("普税贷授信合同签订发生异常：", e);
            return new String[]{EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), e.getMessage()};
        }
    }

    private void updateArrpvDateAndLmtDate(NlsCreditInfo nlsCreditInfo, LmtPrdContVO lmtPrdContVO, String openday) throws Exception {
        //更新授信申请日期
        nlsCreditInfo.setApprvDate(openday);
        int i = nlsCreditInfoDao.updateByPk(nlsCreditInfo);
        if (i != 1) {
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "更新授信申请日期失败，请稍后再试");
        }
        //更新额度的开始时间和到期时间
        lmtPrdContVO.setStartDate(openday);
        lmtPrdContVO.setExpireDate(TimeUtil.addMonth(openday, 12));
        int j = lmtPrdContService.updateByPk(lmtPrdContVO);
        if (j != 1) {
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "更新额度有效期失败，请稍后再试");
        }
    }

    private void insertUploadLog(PsdContResult downResult) {
        psdCertUploadService.insert(downResult.getFileFullPath());
    }

    /**
     * 更新合同状态
     */
    private void updateCtrStatus(CtrLoanContVO ctrLoanContVO, String ctrStatus) throws BizException {
        //状态一样 无需进行变更
        if (ctrStatus.equals(ctrLoanContVO.getContState())) {
            return;
        }
        ctrLoanContVO.setContState(ctrStatus);
        ctrLoanContVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        int i = ctrLoanContService.updateByPk(ctrLoanContVO);
        if (i != 1) {
            throw new BizException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "更新合同状态失败，请稍后再试");
        }
    }

    /**
     * 根据客户ID获取客户信息
     */
    private CusIndivVO getCustInfo(String cusId) throws OcmSystemException {
        CusIndivVO cusIndivVO = new CusIndivVO();
        cusIndivVO.setCusId(cusId);
        cusIndivVO = cusIndivService.queryByPk(cusIndivVO);
        if (Objects.isNull(cusIndivVO)) {
            throw new OcmSystemException("根据客户号：" + cusId + "，查询到的客户信息为空！");
        }
        return cusIndivVO;
    }

    /**
     * 安心签开户
     *
     * @param nlsCreditInfo
     * @param cusIndivVO
     * @throws ExternalSysException
     * @throws OcmSystemException
     */
    private void execute3001(NlsCreditInfo nlsCreditInfo, CusIndivVO cusIndivVO) throws OcmSystemException {
        PsdContResult psdContResult = psdContService.openAccount(nlsCreditInfo.getCusName(), nlsCreditInfo.getCertType(), nlsCreditInfo.getCertCode(), nlsCreditInfo.getEmail(), nlsCreditInfo.getIndivMobile(), nlsCreditInfo.getIndivRsdAddr(), nlsCreditInfo.getLmtApplySeq());
        if (!psdContResult.isRetFlag()) {
            throw new OcmSystemException(psdContResult.getMsg());
}
        cusIndivVO.setAxqUsrId(psdContResult.getAxqUserId());
                int cusUpdNum = cusIndivService.updateByPk(cusIndivVO);
                if (cusUpdNum < 0) {
        if (logger.isErrorEnabled()) {
        logger.error("【普税贷合同签订服务】授信申请流水号：" + nlsCreditInfo.getLmtApplySeq() + "更新安心签开户号到客户信息表(cus_indiv)出错!");
        }
        throw new OcmSystemException("【普税贷合同签订服务】授信申请流水号：" + nlsCreditInfo.getLmtApplySeq() + "更新安心签开户号到客户信息表出错!");
        }
        logger.info("======>【普税贷合同签订服务】调用cfca签章开户接口【3201】结束<====== 授信申请流水号：" + nlsCreditInfo.getLmtApplySeq());
        }

    private void execute3203(SxCtrInfo sxCtrInfo, NlsCreditInfo nlsCreditInfo, CusIndivVO cusIndivVO, CtrLoanContVO ctrLoanContVO, String contType, CfcaSignInfoVO cfcaSignInfoVO) throws Exception {
        PsdContResult psdContResult = psdContService.signature(nlsCreditInfo.getLmtApplySeq(), cusIndivVO.getAxqUsrId(), "sxcont.pdf", "个人综合授信合同", getLocalCtrParamMap(sxCtrInfo, ctrLoanContVO.getContNo()));
        logger.error("签订授信合同-合同签署（3203）完成，授信申请流水号为：[{}],签署结果为：[{}]", sxCtrInfo.getCrdtAppFlowNo(), psdContResult.toString());
        if (psdContResult.isRetFlag()) {
            // 保存合同签章记录数据
            insertCfcaSignInfo(nlsCreditInfo, ctrLoanContVO, cfcaSignInfoVO, psdContResult.getAxqContNo(), psdContResult.getAxqSignTime());
            //updateCtrContInfo(nlsCreditInfo.getLmtApplySeq(), contType);
        }else {
            throw new OcmSystemException("合同签署失败" + psdContResult.getMsg());
        }
    }

    /**
     * 获取合同填写参数MAP
     */
    private Map<String, String> getLocalCtrParamMap(SxCtrInfo sxCtrInfo, String ctrNo) {
        logger.info("【普税贷合同签订服务】组装合同模板填写参数开始 授信申请流水号 ：" + sxCtrInfo.getCrdtAppFlowNo());
        Map<String, String> map = new HashMap<String, String>();
        map.put("ctrNo", ctrNo);
        map.put("addrA", PsdConstantSet.ZH_ADDR);
        map.put("postA", PsdConstantSet.ZH_POST);
        map.put("telA", PsdConstantSet.ZH_TEL);
        map.put("certTypeB", getCertTyName(sxCtrInfo.getCertTp()));
        map.put("certNoB", sxCtrInfo.getCertNo());
        map.put("postB", sxCtrInfo.getPstcd());
        map.put("telB", sxCtrInfo.getCtcTelNo());
        map.put("emailB", sxCtrInfo.getEmail());
        map.put("addrB", sxCtrInfo.getResdntAddr());
        map.put("amountBig1", sxCtrInfo.getLrgLoanAmt().length() > 3 ? sxCtrInfo.getLrgLoanAmt().substring(0, 4) : sxCtrInfo.getLrgLoanAmt());
        map.put("amountBig2", sxCtrInfo.getLrgLoanAmt().length() > 3 ? sxCtrInfo.getLrgLoanAmt().substring(4, sxCtrInfo.getLrgLoanAmt().length()) : "");
        map.put("amountSmal", String.valueOf(sxCtrInfo.getSmlLoanAmt()));
        map.put("cusNameB", sxCtrInfo.getCustNm());
        map.put("identNoB", sxCtrInfo.getCertNo());
        map.put("signDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
        return map;
    }


    /**
     * 保存合同签章记录
     *
     * @throws OcmSystemException
     * @author qiuyf
     * @version 0.1 初始为0.1,后续变更则修改
     * @since 2019年4月26日 上午10:53:53
     */
    private void insertCfcaSignInfo(NlsCreditInfo nlsCreditInfoVO, CtrLoanContVO ctrLoanContVO, CfcaSignInfoVO cfcaSignInfoVO, String axqContNo, String time) throws OcmSystemException {
        //申请流水号
        cfcaSignInfoVO.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        //产品id
        cfcaSignInfoVO.setPrdId(nlsCreditInfoVO.getPrdId());
        //产品代码
        cfcaSignInfoVO.setPrdCode(nlsCreditInfoVO.getPrdCode());
        //产品名称
        cfcaSignInfoVO.setPrdName(nlsCreditInfoVO.getPrdName());
        //合同号
        cfcaSignInfoVO.setContNo(ctrLoanContVO.getContNo());
        //安心签合同号
        cfcaSignInfoVO.setCfcaContNo(axqContNo);
        //客户号
        cfcaSignInfoVO.setCusId(nlsCreditInfoVO.getCusId());
        //客户名称
        cfcaSignInfoVO.setCusName(nlsCreditInfoVO.getCusName());
        //渠道号
        cfcaSignInfoVO.setPrdType(nlsCreditInfoVO.getChannelNo());
        //cfca签署状态 = “未签署”
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        cfcaSignInfoVO.setCfcaSignTime(time);
        int num = cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
        if (num < 0) {
            if (logger.isErrorEnabled()) {
                logger.error("普税贷用信申请【合同签订服务】授信申请流水号为: " + nlsCreditInfoVO.getLmtApplySeq() + " 往cfca加签信息表新增数据出错!");
            }
            throw new OcmSystemException("普税贷用信申请【合同签订服务】授信申请流水号为: " + nlsCreditInfoVO.getLmtApplySeq() + " 往cfca加签信息表新增数据出错!");
        }
        if (logger.isInfoEnabled()) {
            logger.info("======>普税贷用信申请【合同签订服务】保存合同签章记录信息结束<===== 授信申请流水号为：" + nlsCreditInfoVO.getLmtApplySeq());
        }
    }

    /**
     * 更新合同信息
     */
    private void updateCtrContInfo(String applySeq, String contType) throws OcmSystemException {
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        ctrLoanContVO.setSerno(applySeq);
        ctrLoanContVO.setContType(contType);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        if (Objects.isNull(ctrLoanContVO)) {
            logger.error("【合同签订服务】通过授信申请流水号、合同类型获取到合同信息为空！");
            throw new OcmSystemException("普税贷用信申请【合同签订服务】通过授信申请流水号、合同类型获取到合同信息为空！");
        }
        //合同状态 已签订
        //ctrLoanContVO.setContState(CONT_STATUS_200);
        int result = ctrLoanContService.updateByPk(ctrLoanContVO);
        if (result != 1) {
            logger.error("普税贷【合同签订服务】通过授信申请流水号、合同类型更新合同信息为已签订出现异常！");
            throw new OcmSystemException("普税贷【合同签订服务】通过授信申请流水号、合同类型更新合同信息为已签订出现异常");
        }
    }

    /**
     * 获取机构信息
     */
    private SOrgVO getSOrg(String orgCode) throws OcmSystemException {
        SOrgVO sOrgVO = new SOrgVO();
        sOrgVO.setOrgCode(orgCode);
        sOrgVO = sOrgService.queryByPk(sOrgVO);
        if (Objects.isNull(sOrgVO)) {
            throw new OcmSystemException("通过机构号【" + orgCode + "】，获取到机构信息为空！");
        }
        return sOrgVO;
    }

    /**
     * 获取额度协议信息
     */
    private LmtPrdContVO getLmtPrdCont(String lmtApplySeq) throws OcmSystemException {
        LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(lmtApplySeq);
        if (Objects.isNull(lmtPrdContVO)) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信协议信息为空！");
        }
        if (null == lmtPrdContVO.getLmtAmt()) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信额度为空！");
        }
        return lmtPrdContVO;
    }

    /**
     * 插入合同信息
     *
     * @param nlsCreditInfo
     * @param lmtPrdContVO
     * @return
     * @throws Exception
     */
    private CtrLoanContVO insertLoanCtrContract(String openDay, NlsCreditInfo nlsCreditInfo, LmtPrdContVO lmtPrdContVO, SxCtrInfo sxCtrInfo) throws Exception {
        // 查询客户的授信信息
        Optional.ofNullable(nlsCreditInfo).orElseThrow(() -> new BizException("授信流水号为【" + nlsCreditInfo.getLmtApplySeq() + "】的授信信息不存在"));
        // 查询客户的授信协议信息
        //贷款金额
        logger.info("************开始向合同表插入数据！************");
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        //借款合同
        ctrLoanContVO.setContNo(nlsCreditInfo.getLmtApplySeq());//合同编号
        ctrLoanContVO.setSerno(nlsCreditInfo.getLmtApplySeq());//授信申请流水号
        ctrLoanContVO.setLmtContNo(lmtPrdContVO.getLmtContNo());//授信协议编号
        ctrLoanContVO.setPrdCode(nlsCreditInfo.getPrdCode());
        ctrLoanContVO.setCusId(nlsCreditInfo.getCusId());
        ctrLoanContVO.setChannelCode(nlsCreditInfo.getChannelNo());
        ctrLoanContVO.setPrdId(nlsCreditInfo.getPrdId());
        ctrLoanContVO.setPrdName(nlsCreditInfo.getPrdName());
        ctrLoanContVO.setContAmt(nlsCreditInfo.getApplyAmt());

        ctrLoanContVO.setCusName(sxCtrInfo.getCustNm());//客户名称
        ctrLoanContVO.setCertType(sxCtrInfo.getCertTp());//证件类型
        ctrLoanContVO.setCertCode(sxCtrInfo.getCertNo());//证件号码
        ctrLoanContVO.setContAmt(sxCtrInfo.getSmlLoanAmt());//合同金额
        ctrLoanContVO.setTermTimeType(nlsCreditInfo.getTermType());//期限时间类型

        ctrLoanContVO.setLoanTerm(BigDecimal.valueOf(12));//期限
        ctrLoanContVO.setCalFloatingRate(BigDecimal.ZERO);//利率浮动比，普税贷固定利率
        ctrLoanContVO.setRepaymentMode(nlsCreditInfo.getRepaymentMode());//还款方式
        //当前时间--营业日期
        //ctrLoanContVO.setSignDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));//合同签订日期
        ctrLoanContVO.setSignDate(openDay);//合同签订日期
        ctrLoanContVO.setContState("101");//合同状态
        ctrLoanContVO.setContType(ConsoleConstant.CONT_TYPE_01);
        //乙方信息
        //居住地址
        ctrLoanContVO.setResdntAddr(sxCtrInfo.getResdntAddr());
        //邮编
        ctrLoanContVO.setPstcd(sxCtrInfo.getPstcd());
        //客户传真
        ctrLoanContVO.setClnttFax(sxCtrInfo.getClnttFax());
        //联系电话
        ctrLoanContVO.setCtcTelNo(sxCtrInfo.getCtcTelNo());
        //邮箱
        ctrLoanContVO.setEmail(sxCtrInfo.getEmail());
        //大写贷款金额
        ctrLoanContVO.setLrgLoanAmt(sxCtrInfo.getLrgLoanAmt());
        // 创建时间
        ctrLoanContVO.setCreateTime(TimeUtil.getCurrentDateTime());
        ctrLoanContVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        ctrLoanContVO.setLmtContNo(lmtPrdContVO.getLmtContNo());
        logger.info("************向合同表插入的借款合同为：" + "【" + ctrLoanContVO.toString() + "】");
        int count2 = ctrLoanContService.insertCtrLoanCont(ctrLoanContVO);
        if (count2 == -1) {
            logger.error("普税贷授信申请流水号:【" + nlsCreditInfo.getLmtApplySeq() + "】 插入借款合同异常!");
            throw new BizException(EsbRetCodeStandard.SJCLYC.getValue(), "插入借款合同异常!");
        } else {
            logger.info("************向合同表插入借款合同成功！************");
        }
        return ctrLoanContVO;
    }

    //根据证件类型获取证件中文名
    public static String getCertTyName(String certTy) {
        if ("00000".equals(certTy)) {
            return "未知证件类型";
        }

        if ("10000".equals(certTy)) {
            return "对私身份证件";
        }

        if ("10100".equals(certTy)) {
            return "居民身份证";
        }

        if ("10200".equals(certTy)) {
            return "临时身份证";
        }

        if ("10300".equals(certTy)) {
            return "户口簿";
        }

        if ("10400".equals(certTy)) {
            return "护照";
        }

        if ("10401".equals(certTy)) {
            return "普通护照";
        }

        if ("10402".equals(certTy)) {
            return "外交护照";
        }

        if ("10403".equals(certTy)) {
            return "公务护照";
        }

        if ("10404".equals(certTy)) {
            return "因公普通护照";
        }

        if ("10405".equals(certTy)) {
            return "香港特别行政区护照";
        }

        if ("10406".equals(certTy)) {
            return "澳门特别行政区护照";
        }

        if ("10407".equals(certTy)) {
            return "台湾护照";
        }

        if ("10408".equals(certTy)) {
            return "外国护照";
        }

        if ("10500".equals(certTy)) {
            return "军人身份证件";
        }

        if ("10501".equals(certTy)) {
            return "士兵证";
        }

        if ("10502".equals(certTy)) {
            return "军官证";
        }

        if ("10503".equals(certTy)) {
            return "文职干部证";
        }

        if ("10504".equals(certTy)) {
            return "军官退休证";
        }

        if ("10505".equals(certTy)) {
            return "文职干部退休证";
        }

        if ("10506".equals(certTy)) {
            return "军事学员证";
        }

        if ("10507".equals(certTy)) {
            return "军队离休干部荣誉证";
        }

        if ("10600".equals(certTy)) {
            return "武警身份证件";
        }

        if ("10601".equals(certTy)) {
            return "武警士兵证";
        }

        if ("10602".equals(certTy)) {
            return "警官证";
        }

        if ("10603".equals(certTy)) {
            return "武警文职干部证";
        }

        if ("10604".equals(certTy)) {
            return "武警军官退休证";
        }

        if ("10605".equals(certTy)) {
            return "武警文职干部退休证";
        }

        if ("10700".equals(certTy)) {
            return "港澳台居民有效身份证件";
        }

        if ("10701".equals(certTy)) {
            return "港澳居民来往内地通行证";
        }

        if ("10702".equals(certTy)) {
            return "港澳居民身份证";
        }

        if ("10703".equals(certTy)) {
            return "台湾居民来往大陆通行证";
        }

        if ("10704".equals(certTy)) {
            return "台湾居民来往大陆通行证（一次有效）";
        }

        if ("10705".equals(certTy)) {
            return "台湾居民身份证";
        }

        if ("10706".equals(certTy)) {
            return "台湾居民定居证";
        }

        if ("10707".equals(certTy)) {
            return "澳门特别行政区旅行证";
        }

        if ("10708".equals(certTy)) {
            return "香港居民身份证";
        }

        if ("10709".equals(certTy)) {
            return "澳门居民身份证";
        }

        if ("10800".equals(certTy)) {
            return "内地居民往来港澳台有效身份证件";
        }

        if ("10801".equals(certTy)) {
            return "往来港澳通行证";
        }

        if ("10802".equals(certTy)) {
            return "前往港澳通行证";
        }

        if ("10803".equals(certTy)) {
            return "大陆居民往来台湾通行证";
        }

        if ("10804".equals(certTy)) {
            return "因公往来香港澳门特别行政区通行证";
        }

        if ("10900".equals(certTy)) {
            return "外国人永久居留证";
        }

        if ("11000".equals(certTy)) {
            return "外国人居留证";
        }

        if ("11100".equals(certTy)) {
            return "驾驶证";
        }

        if ("11101".equals(certTy)) {
            return "机动车驾驶证";
        }

        if ("11102".equals(certTy)) {
            return "飞机驾驶证";
        }

        if ("11103".equals(certTy)) {
            return "船舶驾驶证";
        }

        if ("11200".equals(certTy)) {
            return "边民出入境通行证";
        }

        if ("12300".equals(certTy)) {
            return "学生证";
        }

        if ("12400".equals(certTy)) {
            return "退休证";
        }

        if ("12500".equals(certTy)) {
            return "工作证";
        }

        if ("12600".equals(certTy)) {
            return "执行公务证";
        }

        if ("12700".equals(certTy)) {
            return "回乡证";
        }

        if ("12800".equals(certTy)) {
            return "文职证";
        }

        if ("19999".equals(certTy)) {
            return "其它个人证件";
        }

        if ("20000".equals(certTy)) {
            return "对公证件";
        }

        if ("20100".equals(certTy)) {
            return "统一社会信用代码";
        }

        if ("20200".equals(certTy)) {
            return "企业登记代码";
        }

        if ("20300".equals(certTy)) {
            return "工商登记证";
        }

        if ("20400".equals(certTy)) {
            return "股东代码证";
        }

        if ("20500".equals(certTy)) {
            return "企业营业执照";
        }

        if ("20600".equals(certTy)) {
            return "组织机构代码证";
        }

        if ("20700".equals(certTy)) {
            return "税务登记证";
        }

        if ("20701".equals(certTy)) {
            return "税务登记证（国税）";
        }

        if ("20702".equals(certTy)) {
            return "税务登记证（地税）";
        }

        if ("20800".equals(certTy)) {
            return "域名注册证";
        }

        if ("20900".equals(certTy)) {
            return "开户许可证";
        }

        if ("20901".equals(certTy)) {
            return "军队开户许可证";
        }

        if ("21000".equals(certTy)) {
            return "外汇许可证";
        }

        if ("21100".equals(certTy)) {
            return "企业外管代码";
        }

        if ("21200".equals(certTy)) {
            return "中征码";
        }

        if ("21300".equals(certTy)) {
            return "金融许可证号";
        }

        if ("21400".equals(certTy)) {
            return "保险业务许可证";
        }

        if ("21500".equals(certTy)) {
            return "证券业务许可证";
        }

        if ("21600".equals(certTy)) {
            return "证监会代码证号";
        }

        if ("21700".equals(certTy)) {
            return "进出口经营权许可证书";
        }

        if ("21800".equals(certTy)) {
            return "外商企业投资登记证书";
        }

        if ("21900".equals(certTy)) {
            return "审批文号";
        }

        if ("22000".equals(certTy)) {
            return "技术监督局编号";
        }

        if ("22100".equals(certTy)) {
            return "人行金融机构代码";
        }

        if ("22200".equals(certTy)) {
            return "银行swift bic";
        }

        if ("22300".equals(certTy)) {
            return "联行行号";
        }

        if ("22400".equals(certTy)) {
            return "外汇管理局印单局代码";
        }

        if ("22500".equals(certTy)) {
            return "FCI编号";
        }

        if ("22600".equals(certTy)) {
            return "事业法人证书";
        }

        if ("22700".equals(certTy)) {
            return "收费许可证";
        }

        if ("22800".equals(certTy)) {
            return "资质证书";
        }

        if ("22900".equals(certTy)) {
            return "下属机构证书";
        }

        if ("23100".equals(certTy)) {
            return "支付业务许可证";
        }

        if ("23200".equals(certTy)) {
            return "社团法人证书";
        }

        if ("23300".equals(certTy)) {
            return "民办非企业登记证";
        }

        if ("23400".equals(certTy)) {
            return "外国驻华机构登记证";
        }

        if ("23500".equals(certTy)) {
            return "外地常设机构登记证";
        }

        if ("23600".equals(certTy)) {
            return "特殊机构代码";
        }

        if ("23700".equals(certTy)) {
            return "行政机关";
        }

        if ("23800".equals(certTy)) {
            return "社会团体";
        }

        if ("23900".equals(certTy)) {
            return "登记文件";
        }

        if ("24100".equals(certTy)) {
            return "批文或批复";
        }

        if ("24200".equals(certTy)) {
            return "开户证明";
        }

        if ("24300".equals(certTy)) {
            return "企业名称预先核准通知书";
        }

        if ("24400".equals(certTy)) {
            return "事业社团法人证书";
        }

        if ("24500".equals(certTy)) {
            return "高新技术企业认定证书";
        }

        if ("24600".equals(certTy)) {
            return "建筑业企业资质证书";
        }

        if ("24700".equals(certTy)) {
            return "社会福利企业证书";
        }

        if ("24800".equals(certTy)) {
            return "机构信用代码";
        }

        if ("29999".equals(certTy)) {
            return "其它对公证件";
        }

        if ("99999".equals(certTy)) {
            return "其它证件";
        }

        if ("10409".equals(certTy)) {
            return "外交官证";
        }

        if ("10410".equals(certTy)) {
            return "使（领事）馆证";
        }

        if ("11104".equals(certTy)) {
            return "海员证";
        }

        if ("10411".equals(certTy)) {
            return "外国人身份证件";
        }

        if ("12301".equals(certTy)) {
            return "高校毕业生自主创业证";
        }

        if ("12302".equals(certTy)) {
            return "就业失业登记证";
        }

        if ("12304".equals(certTy)) {
            return "离休证";
        }

        if ("10507".equals(certTy)) {
            return "城镇退役士兵自谋职业证";
        }

        if ("10508".equals(certTy)) {
            return "随军家属身份证明";
        }

        if ("10509".equals(certTy)) {
            return "中国人民解放军军官转业证书";
        }

        if ("10510".equals(certTy)) {
            return "中国人民解放军义务兵退出现役证";
        }

        if ("10511".equals(certTy)) {
            return "中国人民解放军士官退出现役证";
        }

        if ("12303".equals(certTy)) {
            return "就业创业证";
        }

        if ("10301".equals(certTy)) {
            return "医学出生证明";
        }

        return "身份证";

    }


    @Autowired
    private ImageBizDetailService imageBizDetailService;

    /**
     * 插入记录到影响明细表
     *
     * @param nlsCreditInfoVO
     * @param imgType
     * @param fileName
     * @param filePath
     */
    private void insertImageBizDetail(NlsCreditInfo nlsCreditInfoVO, String imgType, String fileName, String filePath) {
        logger.info(nlsCreditInfoVO.getLmtApplySeq(),"开始添加记录到insertImageBizDetail");
        ImageBizDetailVO imageBizDetail = new ImageBizDetailVO();
        imageBizDetail.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        imageBizDetail.setBizStage("授信合同");
        imageBizDetail.setFileDesc("普税贷授信合同");
        imageBizDetail.setFileName(fileName);
        imageBizDetail.setFilePath(filePath);
        imageBizDetail.setImageId(imgType);
        imageBizDetail.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizDetail.setImageType(imgType);
        imageBizDetailService.insertImageBizDetail(imageBizDetail);
    }

    @Autowired
    private ImageBizInfoService imageBizInfoService;
    /**
     * 插入数据到影像业务信息
     *
     * @param nlsCreditInfoVO 目标文件
     */
    private void insertImageBizInfo(NlsCreditInfo nlsCreditInfoVO) {
        logger.info(nlsCreditInfoVO.getLmtApplySeq(),"开始添加记录到insertImageBizInfo");
        ImageBizInfoVO param = new ImageBizInfoVO();
        param.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        if (!Objects.isNull(imageBizInfoService.queryByPk(param))) {
            return;
        }
        ImageBizInfoVO imageBizInfo = new ImageBizInfoVO();
        imageBizInfo.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        imageBizInfo.setCreateDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        imageBizInfo.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizInfo.setCusId(nlsCreditInfoVO.getCusId());
        imageBizInfo.setCusName(nlsCreditInfoVO.getCusName());
        imageBizInfo.setPrdId(nlsCreditInfoVO.getPrdId());
        imageBizInfo.setPrdCode(nlsCreditInfoVO.getPrdCode());
        imageBizInfo.setPrdName(nlsCreditInfoVO.getPrdName());
        //如下信息先赋空值
        imageBizInfo.setSoltImageAccept("");
        imageBizInfo.setSoltImageCfca("");
        imageBizInfo.setSoltImageThird1("");
        imageBizInfo.setSoltImageThird2("");
        imageBizInfoService.insertOrUpdateImageBizInfoVO(imageBizInfo);
    }

    private void insertSqsRecord(SxCtrInfo sxCtrInfo,NlsCreditInfo psdCreditApplyReqBean,CtrLoanContVO ctrLoanContVO) {
        Map<String, String> localCtrParamMap = getLocalCtrParamMap(sxCtrInfo, ctrLoanContVO.getContNo());
        SignatureRecordVO tmSignatureRecordVO = new SignatureRecordVO();
        tmSignatureRecordVO.setId(UUIDUtil.getUUID());
        tmSignatureRecordVO.setPrdId(PsdConstantSet.prdId);
        tmSignatureRecordVO.setApplySeq(psdCreditApplyReqBean.getLmtApplySeq());
        tmSignatureRecordVO.setLinkType(3);
        tmSignatureRecordVO.setPolFileType(PsdConstantSet.PSD_SX_CONT_TM_TYPE);
        tmSignatureRecordVO.setRetryNum(0);
        tmSignatureRecordVO.setCreateTime(new Date());
        tmSignatureRecordVO.setLastUpdateTime(new Date());
        tmSignatureRecordVO.setSiuSta(0);
        tmSignatureRecordVO.setSiuFillInfo(JSONObject.toJSONString(localCtrParamMap));
        sqsSignatureService.insertRecord(tmSignatureRecordVO);
    }

}
